package com.credithc.customers.manager.service.impl;

import com.credithc.baseserv.core.codes.CoreCodes;
import com.credithc.baseserv.core.exception.BsException;
import com.credithc.baseserv.core.message.Message;
import com.credithc.customers.base.constants.CustomerConstants;
import com.credithc.customers.manager.client.AuthClient;
import com.credithc.customers.manager.client.SaasClient;
import com.credithc.customers.manager.ro.TokenRo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
/**
 * @description: 云平台对接公用方法
 * @author: denghx
 * @date: 2019/10/9 16:49
 * @param: null
 * @return:
 */
@Service
@Slf4j
public class AuthorizationServiceImpl {

    @Autowired
    private AuthClient authClient;

    @Autowired
    private SaasClient saasClient;

//    @Autowired
//    private CompanyClient companyClient;

    /*@Autowired
    private OcrBizSystemService bizSystemService;*/

    /**
     * 获取渠道查询权限
     *
     * @param token
     * @param request
     * @return
     */
    public List<String> authChannelRo(String token, HttpServletRequest request) {
        TokenRo authData = getAuthData(token, request);
        List<String> channelNos = new ArrayList<>();
        if (authData != null) {
            //判断时否时租户管理员 是：查询所有 否：根据渠道ID查询
            String productCode = authData.getProductCode();
            log.info("获取渠道的查询权限:productCode=" + productCode);
            channelNos.add(productCode);
        }
        return channelNos;
    }


    /**
     * 获取当前用户的渠道ID
     *
     * @param token
     * @param request
     * @return
     */
    /*public List<String> authChannelNo(String token, HttpServletRequest request) {
        TokenRo authData = getAuthData(token, request);
        List<String> channelNos = new ArrayList<>();
        if (authData != null) {
            String productCode = authData.getProductCode();
            channelNos.add(productCode);
        }
        return channelNos;
    }*/

    /**
     * 根据token和request查询数据权限
     *
     * @param token
     * @param request
     * @return
     */
    public TokenRo getAuthData(String token, HttpServletRequest request) {
        if (StringUtils.isNotBlank(token) && !CustomerConstants.LOCAL_ADDR.equals(request.getRemoteAddr())) {
            log.info("开始查询数据权限......");
            Message<TokenRo> userByToken = authClient.getUserInfoByToken(token);
            log.info("数据权限查询结果:" + userByToken.toString());
            if (CoreCodes.CORE_SUCCESS == userByToken.getCode()) {
                TokenRo authData = userByToken.getData();
                if (CustomerConstants.NOT_TENANT.equals(authData.getCompanyId())) {
                    log.error("当前登录用户不是租户......");
                    throw new BsException(CoreCodes.CORE_SYS_ERROR, "当前登录用户不是租户......");
                } else {
                    return authData;
                }
            }
            log.info("结束查询数据权限......");
        }
        return null;
    }

    /**
     * 给运营平台使用
     *
     * @param token
     * @param request
     * @return
     */
    /*public TokenRo getOperateAuthData(String token, HttpServletRequest request) {
        if (StringUtils.isNotBlank(token) && !OcrConstant.LOCAL_ADDR.equals(request.getRemoteAddr())) {
            log.info("开始查询数据权限......");
            Message<TokenRo> userByToken = authClient.getUserInfoByToken(token);
            log.info("数据权限查询结果:" + userByToken.toString());
            if (CoreCodes.CORE_SUCCESS == userByToken.getCode()) {
                TokenRo authData = userByToken.getData();
                return userByToken.getData();
            }
            log.info("结束查询数据权限......");
        }
        return null;
    }*/

//    /**
//     * 根据companyID获取渠道ID集合
//     *
//     * @param authData
//     * @return
//     */
//    private List<Integer> getChannelIds(TokenRo authData) {
//        List<String> channelCodes = getChannelCodes(authData);
//        List<Integer> channelIds = new ArrayList<>(10);
//        for (String channelCode : channelCodes) {
//            Channel channel = channelService.selectChannelByCode(channelCode);
//            if (channel != null) {
//                channelIds.add(channel.getId());
//            }
//        }
//        return channelIds;
//    }

    /**
     * 获取渠道编码
     *
     * @param authData
     * @return
     */
    /*public List<String> getChannelCodes(TokenRo authData) {
        List<Integer> companyIds = new ArrayList<>(10);
        companyIds.add(authData.getCompanyId());
        Message<List<ProductRo>> productList = saasClient.getProductList(companyIds);
        List<ProductRo> data = productList.getData();
        log.info("获取租户管理员产品列表：" + Arrays.toString(data.stream().map(ProductRo::getCode).toArray()));
        return data.stream().map(ProductRo::getCode).collect(Collectors.toList());
    }*/

    /**
     * 封装foreach参数
     *
     * @param params
     * @return
     */
   /* private String buildForeachParams(List<Integer> params) {
        StringBuffer bf = new StringBuffer();
        if (params != null) {
            params.forEach(p -> {
                bf.append(p);
                bf.append(",");
            });
            if (bf.length() > 0) {
                bf.deleteCharAt(bf.toString().length() - 1);
            }
        }
        return bf.toString();
    }*/

    /*public PageInfo<CompanyRo> getCompanyList() {


        Message<List<CompanyRo>> cacheData = companyClient.getCacheData();
        List<CompanyRo> companyVos = cacheData.getData();
        List<String> comNames = new ArrayList<>();
        Map<String,CompanyRo> comMap = new HashMap<>();
        for (CompanyRo cr:companyVos) {
            comNames.add(cr.getCompanyName());
            comMap.put(cr.getCompanyName(),cr);
        }
        System.out.println(comNames);
        Object[] comNames1 = comNames.toArray();
        Arrays.sort(comNames1, new PinyinComparator());
        System.out.println(JSONObject.toJSONString(comNames1));

        List<CompanyRo> companyRos = new ArrayList<>();
        for (int i = 0;i<comNames1.length ;i++) {
            companyRos.add( comMap.get(comNames1[i]));
        }

        PageInfo<CompanyRo> pageInfo = new PageInfo<>();
        pageInfo.setList(companyRos);
        return pageInfo;
    }*/

}
